<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.baseName" placeholder="基地名称" clearable style="width: 120px" class="filter-item" size="mini" round @change="handleFilter">
        <el-option v-for="item in baseoption" :key="item.label" :label="item.label" :value="item.label" />
      </el-select>
      <el-input v-model="listQuery.sensorName" placeholder="输入传感器关键字" style="width: 200px;margin-left: 10px" class="filter-item" size="mini" round @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" size="mini" style="margin-left: 10px;" round @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="exportToExcel">
        模板下载
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="delData">
        批量删除
      </el-button>
      <el-upload
        ref="upload"
        class="upload-demo"
        action="doUpload"
        :limit="1"
        :file-list="fileList"
        style="margin-left: 5px; float:right"
        :before-upload="beforeUpload"
      >
        <el-button size="mini" round style="margin-left: 5px; float:right">导入</el-button>
      </el-upload>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="77" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="远程控制设备名称" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remoteControlDeviceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="远程控制类型" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.deviceTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.deviceNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="基地名称" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.baseName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="远程控制状态" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remoteStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="首页显示" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.homeShow }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="基地名称" prop="baseId">
          <el-select v-model="temp.baseId" placeholder="全部基地" clearable style="width: 120px" class="filter-item" @change="selectregionName">
            <el-option v-for="item in baseoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="regionId">
          <el-select v-model="temp.regionId" placeholder="土壤情况" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in regionoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="deviceTypeId">
          <el-select v-model="temp.deviceTypeId" placeholder="全部远程控制类型" clearable style="width: 120px" class="filter-item">
            <el-option v-for="item in deviceTypeoption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="远程控制设备名称" prop="remoteControlDeviceName">
          <el-input v-model="temp.remoteControlDeviceName" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input v-model="temp.deviceNumber" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="所属节点" prop="belongNode">
          <el-input v-model="temp.belongNode" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="设备地址" prop="deviceAddress">
          <el-input v-model="temp.deviceAddress" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="传感器通讯号" prop="sensorCommunicaton">
          <el-input v-model="temp.sensorCommunicaton" placeholder="1-20个字符" />
        </el-form-item>
        <el-form-item label="远程控制状态" prop="remoteStatus">
          <el-checkbox-group v-model="checkedremote" @change="handlechange1">
            <el-checkbox v-for="item in remoteoption" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="连接状态" prop="connectStatus">
          <el-checkbox-group v-model="checkedconnect" @change="handlechange3">
            <el-checkbox v-for="item in connectoption" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="首页显示" prop="homeShow">
          <el-checkbox-group v-model="checkedhome" @change="handlechange2">
            <el-checkbox v-for="item in homeoption" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          size="mini"
          @click="dialogStatus==='create'?createData():updateData()"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getmutualList, addmutualList, deletemutualList, deletemutualLists, updatemutualList, uploadmutualList } from '@/api/mutual'
import { getIdandName, getregionList, getbaseList } from '@/api/type'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { isPhone, isName, isStunum } from '@/utils/validate'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      checkedremote: [],
      checkedhome: [],
      checkedconnect: [],
      // isNeedAudit:true,
      sels: [],
      tableKey: 0,
      list: '',
      total: 0,
      listLoading: true,
      listQuery: {
        baseName: '',
        remoteControlDeviceName: '',
        page: 1,
        limit: 20
      },
      remoteoption: ['开启', '禁用'],
      homeoption: ['显示', '隐藏'],
      connectoption: ['启用', '禁用'],
      baseoption: [],
      regionoption: [],
      deviceTypeoption: [],
      temp: {
        item: [],
        moduleType: '',
        controlInteractionId: '',
        remoteControlDeviceName: '',
        deviceNumber: '',
        belongNode: '',
        deviceAddress: '',
        remoteStatus: '',
        connectStatus: '',
        homeShow: '',
        deviceTypeId: '',
        deviceTypeName: '',
        baseId: '',
        baseName: '',
        regionId: '',
        regionName: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改基本信息',
        create: '新建基本信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        studentName: [{ required: true, message: '姓名不能为空', trigger: 'blur' },
          { type: 'string', max: 20, message: '姓名不能大于20位', trigger: 'blur' },
          { validator: isName, trigger: 'blur' }
        ],
        phoneNumber: [{ required: true, message: '手机号不可为空', trigger: 'blur' },
          // { type: 'string', min: 11, message: '手机号不允许小于11位', trigger: 'blur' },
          { validator: isPhone, trigger: 'blur' }],
        studentId: [{ required: true, message: '学号不能为空', trigger: 'blur' },
          { type: 'string', max: 20, message: '学号不能大于20位', trigger: 'blur' },
          { validator: isStunum, trigger: 'blur' }],
        class: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
        grade: [{ required: true, message: '年级不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.temp.moduleType = '控制交互类'
    getIdandName(this.temp).then(res => {
      for (let i = 0; i < res.data.length; i++) {
        this.deviceTypeoption.push({ value: `${res.data[i].deviceTypeId}`, label: `${res.data[i].deviceTypeName}` })
      }
    })
    getbaseList(this.temp).then(res => {
      for (let i = 0; i < res.data.records.length; i++) {
        this.baseoption.push({ value: `${res.data.records[i].baseId}`, label: `${res.data.records[i].baseName}` })
      }
    })
  },
  methods: {
    selectregionName(value) {
      // console.log(value[0])
      // this.regionoption.empty()
      this.regionoption = []
      getbaseList(this.temp).then(res => {
        // console.log(res.data.records[0])
        for (let i = 0; i < res.data.records.length; i++) {
          if (res.data.records[i].baseId == value) {
            console.log(res.data.records[i].baseName)
            getregionList(this.temp).then(response => {
            // console.log(response.data.records)
              for (let j = 0; j < response.data.records.length; j++) {
                if (response.data.records[j].baseName == res.data.records[i].baseName) {
                  this.regionoption.push({ value: `${response.data.records[j].regionId}`, label: `${response.data.records[j].regionName}` })
                }
              }
            })
          }
        }
      })
    },
    handlechange1(value) {
      console.log(value[0])
      this.temp.remoteStatus = value[0]
    },
    handlechange2(value) {
      console.log(value[0])
      this.temp.homeShow = value[0]
    },
    handlechange3(value) {
      this.temp.connectStatus = value[0]
    },
    getList() {
      this.listLoading = true
      getmutualList(this.listQuery).then(res => {
      // console.log(res.data)
        this.list = res.data.records
        this.total = res.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1

      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        item: [],
        moduleType: '',
        controlInteractionId: '',
        remoteControlDeviceName: '',
        deviceNumber: '',
        belongNode: '',
        deviceAddress: '',
        remoteStatus: '',
        connectStatus: '',
        homeShow: '',
        deviceTypeId: '',
        deviceTypeName: '',
        baseId: '',
        baseName: '',
        regionId: '',
        regionName: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // console.log(this.temp)
          addmutualList(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleRemove(row, index) {
      this.temp = Object.assign(row, index)
      this.dialogStatus = 'remove'
      this.dialogFormVisible = true
      this.clearValidate()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.isNeedAudit = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // console.log(tempData)
          updatemutualList(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },

    // 删除
    handleDelete(row) {
      console.log(row)
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deletemutualList(row)
        this.getList()
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    selectRow(sels) {
      this.sels = sels
      // console.log(sels.length)
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        for (let i = 0; i < this.sels.length; i++) {
          this.temp.item[i] = this.sels[i].controlInteractionId
        }
        deletemutualLists(this.temp)
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    // 模板下载
    exportToExcel() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          // "id",
          '远程设备控制名称',
          '设备编号',
          '类型',
          '基地名称',
          '区域名称'
          // "楼宇号"
        ]
        const filterVal = [

          'remoteControlDeviceName',
          'deviceNumber',
          'deviceTypeId',
          'baseName',
          'regionName'
          // "isOperatemonitor",
          // "isOperatewfm",
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        return v[j]
      }))
    },

    // 文件导入
    beforeUpload(file) {
      // console.log(file,'文件');
      this.files = file
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return
      }
      if (!isLt5M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return
      }
      this.fileName = file.name
      setTimeout(() => {
        this.submitUpload()
      }, 500)
      return false // 返回false不会自动上传
    },

    // 上传excel
    submitUpload(e) {
      console.log('上传' + this.files.name)
      if (this.fileName == '') {
        this.$message.warning('请选择要上传的文件！')
        return false
      }
      const fileFormData = new FormData()
      fileFormData.append('file', this.files, this.fileName)
      // 调用后台接口函数
      uploadmutualList(fileFormData).then(() => {
        this.$notify({
          title: 'Success',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    }

  }
}
</script>
